const express = require('express');
const router = express.Router();
const upload = require('../middleware/upload');
const { getFileUrl } = require('../utils/fileHelper');
const ResponseCode = require('../utils/responseCode');
const authMiddleware = require('../middleware/auth');

// 上传单个文件
router.post('/file', authMiddleware, upload.single('file'), async (req, res) => {
  try {
    if (!req.file) {
      return res.json({
        code: ResponseCode.PARAM_ERROR,
        message: '请选择要上传的文件'
      });
    }

    // 生成文件访问URL
    const fileUrl = getFileUrl(req.file.path.split('uploads/')[1]);

    res.json({
      code: ResponseCode.SUCCESS,
      message: '上传成功',
      data: {
        url: fileUrl,
        filename: req.file.filename,
        mimetype: req.file.mimetype,
        size: req.file.size
      }
    });
  } catch (error) {
    console.error('文件上传错误:', error);
    res.json({
      code: ResponseCode.SERVER_ERROR,
      message: '文件上传失败，请稍后重试'
    });
  }
});

// 错误处理
router.use((error, req, res, next) => {
  if (error instanceof multer.MulterError) {
    if (error.code === 'LIMIT_FILE_SIZE') {
      return res.json({
        code: ResponseCode.PARAM_ERROR,
        message: '文件大小超出限制'
      });
    }
  }
  res.json({
    code: ResponseCode.SERVER_ERROR,
    message: error.message || '文件上传失败'
  });
});

module.exports = router; 